// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package spec

import (
	"os"
	"os/user"
	"path"
	"path/filepath"

	"github.com/kumose/errors"
	kmoptlocaldata "github.com/kumose/kmopt/pkg/localdata"
	"github.com/kumose/kmopt/pkg/utils"
)

// sub directory names
const (
	KmoptPackageCacheDir     = "packages"
	KmoptClusterDir          = "clusters"
	kmoptAuditDir             = "audit"
	TLSCertKeyDir            = "tls"
	TLSCertKeyDirWithAnsible = "ssl"
	TLSCACert                = "ca.crt"
	TLSCAKey                 = "ca.pem"
	TLSClientCert            = "client.crt"
	TLSClientKey             = "client.pem"
	PFXClientCert            = "client.pfx"
)

var profileDir string

// getHomeDir get the home directory of current user (if they have one).
// The result path might be empty.
func getHomeDir() (string, error) {
	u, err := user.Current()
	if err != nil {
		return "", errors.Trace(err)
	}
	return u.HomeDir, nil
}

var initialized = false

// Initialize initializes the global variables of meta package. If the
// environment variable KMOPT_COMPONENT_DATA_DIR is set, it is used as root of
// the profile directory, otherwise the `$HOME/.kmopt` of current user is used.
// The directory will be created before return if it does not already exist.
func Initialize(base string) error {
	kmoptData := os.Getenv(kmoptlocaldata.EnvNameComponentDataDir)
	kmoptHome := os.Getenv(kmoptlocaldata.EnvNameHome)

	switch {
	case kmoptData != "":
		profileDir = kmoptData
	case kmoptHome != "":
		profileDir = path.Join(kmoptHome, kmoptlocaldata.StorageParentDir, base)
	default:
		homeDir, err := getHomeDir()
		if err != nil {
			return errors.Trace(err)
		}
		profileDir = path.Join(homeDir, ".kmopt", kmoptlocaldata.StorageParentDir, base)
	}

	clusterBaseDir := filepath.Join(profileDir, KmoptClusterDir)
	tidbSpec = NewSpec(clusterBaseDir, func() Metadata {
		return &ClusterMeta{
			Topology: new(Specification),
		}
	})
	initialized = true
	// make sure the dir exist
	return utils.MkdirAll(profileDir, 0755)
}

// ProfileDir returns the full profile directory path of KMOPT.
func ProfileDir() string {
	return profileDir
}

// ProfilePath joins a path under the profile dir
func ProfilePath(subpath ...string) string {
	return path.Join(append([]string{profileDir}, subpath...)...)
}

// ClusterPath returns the full path to a subpath (file or directory) of a
// cluster, it is a subdir in the profile dir of the user, with the cluster name
// as its name.
// It is not guaranteed the path already exist.
func ClusterPath(cluster string, subpath ...string) string {
	return GetSpecManager().Path(cluster, subpath...)
}
